<template>
  <div class="containers">
    <div class="input-bar">
      <el-form ref="modelForm" :model="modelForm" :inline="true" :rules="rules" size="small">
        <div class="filter-container">
          <div class="filter-item">
            <el-form-item prop="modelTypeId" label="流程分类">
              <el-select v-model="modelForm.modelTypeId">
                <el-option v-for="(item, index) in modelTypeList" :key="index" :value="item.value" :label="item.title"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="filter-item">
            <el-form-item prop="modelName" label="流程名称">
              <el-input v-model="modelForm.modelName"/>
            </el-form-item>
          </div>
          <div class="filter-item">
            <el-form-item prop="proInsNameRule" label="实例名称命名规则" label-width="150px">
              <el-input v-model="modelForm.proInsNameRule"/>
            </el-form-item>
          </div>
          <div class="filter-item">
            <el-form-item prop="tableComment" label="对应表单" label-width="80px">
              <el-input placeholder="请选择表单" v-model="modelForm.tableComment" disabled >
                <el-button slot="append" type="primary" icon="el-icon-search" @click="handleForm"></el-button>
              </el-input>
            </el-form-item>
          </div>
          <el-button class="filter-item" type="primary" size="small" @click="handleSave">保存</el-button>
          <el-button class="filter-item" type="primary" size="small" @click="handleRefresh" plain :loading="refreshLoading">刷新</el-button>
        </div>
      </el-form>
    </div>
    <div class="canvas-container">
      <div class="canvas" ref="canvas" />
      <PropertyPanel v-if="bpmnModeler" ref="PropertyPanel" :formTable="formTable" :modeler="bpmnModeler" />
      <!-- <div class="toolbar">
        <a title="download">下载</a>
        <a ref="saveDiagram" href="javascript:" title="download BPMN diagram">BPMN</a>
        <a ref="saveSvg" href="javascript:" title="download as SVG image">SVG</a>
      </div> -->
    </div>
    <el-dialog :visible.sync="formDialogVisible" width="800px" title="选择表单">
      <FormTable ref="FormTable" @callbackFormTable="callbackFormTable"/>
    </el-dialog>
  </div>
</template>

<script>
import BpmnModeler from 'bpmn-js/lib/Modeler' // bpmn-js 设计器
import FormTable from '@/views/workflow/form/components/FormTable'
import PropertyPanel from './components/PropertyPanel' // 属性面板
import BpmData from '@/views/workflow/utils/bpmn/BpmData'
import customTranslateModule from '@/views/workflow/utils/bpmn/customTranslate'
  // 对flowable的扩展
import flowableExtensionModule from 'jp-flowable-bpmn-moddle/lib'
import flowableModdle from 'jp-flowable-bpmn-moddle/resources/flowable'
import { create, save, getModel, defaultXml } from '@/api/workflow/bpmn/model'
import { getDeployInfo } from '@/api/workflow/bpmn/deploy'
import { getInfoById as getTableInfoById } from '@/api/workflow/form/table'
import { getDicTree } from '@/api/dictionary'

export default {
  components: {
    FormTable,
    PropertyPanel
  },
  data() {
    return {
      deploymentId: '',
      bpmnModeler: null,
      element: null,
      bpmData: new BpmData(),
      modelTypeList: [],
      modelForm: {
        modelTypeId: '',
        modelId: '',
        modelName: '',
        proInsNameRule: '',
        tableComment: ''
      },
      rules: {
        modelTypeId: [{ required: true, message: '请选择流程分类', trigger: 'change' }],
        modelName: [{ required: true, message: '请输入模型名称', trigger: 'blur' }],
        proInsNameRule: [{ required: true, message: '请输入实例名称命名规则', trigger: 'blur' }],
        tableComment: [{ required: true, message: '请选择表单', trigger: 'blur' }]
      },
      bpmnXmlStr: '',
      detail: {}, // 模型和流程详情
      formTable: {}, // 对应的表单信息
      formDialogVisible: false,
      refreshLoading: false
    }
  },
  watch: {
    formTable: {
      handler(n, o){
        this.modelForm.tableComment = n.tableComment
      },
      deep: true
    }
  },
  created() {
    this.getModelTypeList()
  },
  mounted() {
    this.modelForm.modelId = this.$route.query.id
    this.deploymentId = this.$route.query.deploymentId
    const canvas = this.$refs.canvas
    // 生成实例
    this.bpmnModeler = new BpmnModeler({
      container: canvas,
      additionalModules: [
        customTranslateModule,
        flowableExtensionModule
      ],
      moddleExtensions: {
        flowable: flowableModdle,
      }
    })

    // // 获取a标签dom节点
    // const downloadLink = this.$refs.saveDiagram
    // const downloadSvgLink = this.$refs.saveSvg
    // // 监听流程图改变事件
    const _this = this
    this.bpmnModeler.on('commandStack.changed', function() {
      _this.saveSVG(function(err, svg) {
      })
      _this.saveDiagram(function(err, xml) {
        console.log(err, xml)
      })
    })
    this.getModelDetail()
  },
  methods: {
    async getModelTypeList() { // 获取流程分类列表
      const id = '013'
      const res = await getDicTree(id)
      this.modelTypeList = res.data
    },
    async getModel() { // 获得远程xml
      let res = undefined
      if (this.deploymentId) { // 当deploymentId有值时，是编辑已部署的流程
        res = await getDeployInfo(this.deploymentId)
      } else if (this.modelForm.modelId) {
        res = await getModel(this.modelForm.modelId)
      }
      if (res && res.data) {
        this.detail = res.data
        this.modelForm.modelTypeId = res.data.processTypeId
        this.modelForm.modelName = res.data.modelName
        this.modelForm.proInsNameRule = res.data.proInsNameRule
        this.bpmnXmlStr = res.data.xml
      }
    },
    async getTableInfo() { // 获得对应的表单信息
      if (this.detail.formTableId) {
        const res = await getTableInfoById(this.detail.formTableId)
        this.formTable = res.data
      }
    },
    async getModelDetail() {
      await this.getModel()
      await this.getTableInfo()
      this.createNewDiagram()
    },
    createNewDiagram() {
      this.bpmnXmlStr = this.bpmnXmlStr || defaultXml()
      // 需要自动为每一个xml添加flowable属性值，否则xml的头部会自动去掉xmlns:flowable（这个属性值没有其他的含义）
      // if (this.bpmnXmlStr.indexOf('flowable:isFlowable="true"') < 0) {
      //   this.bpmnXmlStr = this.bpmnXmlStr.replace('<process' , '<process flowable:isFlowable="true"')
      // }
      // 将字符串转换成图显示出来
      this.bpmnModeler.importXML(this.bpmnXmlStr, err => {
        if (err) {
          console.error(err)
        } else {
          // this.adjustPalette()
          this.setProcessListener()
        }
      })
    },
    setProcessListener() {
      const elements = this.bpmnModeler.get('elementRegistry')
      const processList = elements.filter(element => element.type === 'bpmn:Process')
      if (processList && processList.length) {
        const element = processList[0]
        var moddle = this.bpmnModeler.get('moddle')
        var extensionElements = moddle.create('bpmn:ExtensionElements')
        var taskListenerStart = moddle.create('flowable:ExecutionListener', {
          event: 'start',
          delegateExpression: '${processStartListener}'
        })
        var taskListenerEnd = moddle.create('flowable:ExecutionListener', {
          event: 'end',
          delegateExpression: '${processEndListener}'
        })
        extensionElements.values = [ taskListenerStart, taskListenerEnd ]
        const modeling = this.bpmnModeler.get('modeling')
        modeling.updateProperties(element, {
          'flowable:isFlowable': true,// 需要自动为每一个xml添加flowable属性值（这个属性值任意取值，且没有其他的含义，只需要有一个flowable:xxx就行了），否则xml的头部会自动去掉xmlns:flowable
          extensionElements: extensionElements
        })
      }
    },
    
    handleRefresh() {
      this.refreshLoading = true
      setTimeout(() => {
        this.createNewDiagram()
        this.refreshLoading = false
      }, 500)
    },
    handleForm() { // 点击选择表单
      this.formDialogVisible = true
    },
    callbackFormTable(data) { // 选择表单回调
      this.formTable = data
      this.formDialogVisible = false
    },
    // 调整左侧工具栏排版
    adjustPalette() {
      try {
        // 获取 bpmn 设计器实例
        const canvas = this.$refs.canvas
        const djsPalette = canvas.children[0].children[1].children[4]
        const djsPalStyle = {
          width: '130px',
          padding: '5px',
          background: 'white',
          left: '20px',
          borderRadius: 0
        }
        for (var key in djsPalStyle) {
          djsPalette.style[key] = djsPalStyle[key]
        }
        const palette = djsPalette.children[0]
        const allGroups = palette.children
        allGroups[0].style['display'] = 'none'
        // 修改控件样式
        for (var gKey in allGroups) {
          const group = allGroups[gKey]
          for (var cKey in group.children) {
            const control = group.children[cKey]
            const controlStyle = {
              display: 'flex',
              justifyContent: 'flex-start',
              alignItems: 'center',
              width: '100%',
              padding: '5px'
            }
            if (
              control.className &&
              control.dataset &&
              control.className.indexOf('entry') !== -1
            ) {
              const controlProps = this.bpmData.getControl(
                control.dataset.action
              )
              control.innerHTML = `<div style='font-size: 14px;font-weight:500;margin-left:15px;'>${
                controlProps['title']
              }</div>`
              for (var csKey in controlStyle) {
                control.style[csKey] = controlStyle[csKey]
              }
            }
          }
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 下载为SVG格式,done是个函数，调用的时候传入的
    saveSVG(done) {
      // 把传入的done再传给bpmn原型的saveSVG函数调用
      this.bpmnModeler.saveSVG(done)
    },
    // 下载为SVG格式,done是个函数，调用的时候传入的
    saveDiagram(done) {
      // 把传入的done再传给bpmn原型的saveXML函数调用
      this.bpmnModeler.saveXML({ format: true }, (err, xml) => {
        this.bpmnXmlStr = xml
        done(err, xml)
      })
    },
    handleSave() { // 新增模型（新增的时候是新增模型再新增流程）
      this.$refs['modelForm'].validate(async valid => {
        if (valid) {
          if (this.deploymentId) { // 编辑已部署的流程
            this.handleSaveFlow('', this.deploymentId)
          } else {
            if (this.modelForm.modelId) { // 编辑未部署的流程
              this.handleSaveFlow()
            } else { // 新增
              const post = {
                ...this.modelForm
              }
              const res = await create(post)
              const modelId = res.data
              if (modelId) {
                this.handleSaveFlow(modelId)
              }
            }
          }
        }
      })
    },
    handleSaveFlow(modelId, deploymentId) { // 新增/编辑流程
      // const elements = this.bpmnModeler.get('elementRegistry')
      // const userTasks = elements.filter(element => element.type === 'bpmn:UserTask')
      // 获得起始用户任务节点的layoutId
      // const startUserTask = userTasks.length ? userTasks[0] : null
      // const startLayoutId = startUserTask ? startUserTask.businessObject.$attrs['formLayoutId'] : ''
      // const startTaskId = startUserTask ? startUserTask.id : ''
      const post = {
        modelName: this.modelForm.modelName,
        proInsNameRule: this.modelForm.proInsNameRule,
        formTableId: this.formTable.tableId,
        // startLayoutId: startLayoutId,
        // startTaskId: startTaskId,
        xml: this.bpmnXmlStr.replace(/ bounds="\[object Object\]"/g, '') // bounds="\[object Object\] 是自动添加的多余的属性，保存后会保存，因此手动去除
      }
      if (deploymentId) {
        post['deploymentId'] = deploymentId
      } else {
        post['modelId'] = modelId || this.modelForm.modelId
      }
      save(post).then(res => {
        this.$message.success('保存成功')
        if (modelId){ // 新增成功后跳转回列表页
          this.$router.push({ path: '/workflow/bpmn/index' })
        }
      })
    }
  }
}
</script>

<style lang="scss">
/*左边工具栏以及编辑节点的样式*/
@import "~bpmn-js/dist/assets/diagram-js.css";
@import "~bpmn-js/dist/assets/bpmn-font/css/bpmn.css";
@import "~bpmn-js/dist/assets/bpmn-font/css/bpmn-codes.css";
@import "~bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css";
.containers {
  // position: absolute;
  background-color: #ffffff;
  width: 100%;
  // height: 100%;
  .input-bar {
    padding: 10px;
    border-bottom: 1px solid #f1e8e8;
    .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item {
      margin-bottom: 0;
    }
  }
  .canvas-container {
    position: relative;
    height: 640px;
  }
  .canvas {
    width: 100%;
    height: 100%;
    // padding-right: 300px;
  }
  .bjs-powered-by {
    display: none;
  }
  .toolbar {
    position: absolute;
    top: 20px;
    right: 350px;
    a {
      text-decoration: none;
      margin: 5px;
      color: #409eff;
    }
  }
}
</style>
